<template>
  <el-dialog
      v-model="dialogVisible"
      :title="mode === 'damage' ? '填写报损信息' : '填写报溢信息'"
      width="600px"
      :before-close="handleClose"
      class="AdjustItem"
  >
    <div class="AdjustItem-product" v-if="productDetail">
      <div class="AdjustItem-product-item"><span class="AdjustItem-product-label">商品编码：</span>{{
          productDetail.code
        }}
      </div>
      <div class="AdjustItem-product-item"><span class="AdjustItem-product-label">名称：</span>{{ productDetail.name }}
      </div>
      <div class="AdjustItem-product-item"><span
          class="AdjustItem-product-label">分类：</span>{{ productDetail.categoryName || '-' }}
      </div>
    </div>

    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="AdjustItem-form">
      <el-form-item label="日期" prop="date">
        <el-date-picker v-model="form.date" type="date" placeholder="日期" class="AdjustItem-form-input" disabled />
      </el-form-item>
      <el-form-item :label="mode==='damage' ? '报损数量' : '报溢数量'" prop="quantity">
        <div class="AdjustItem-qty">
          <el-input-number v-model="form.quantity" :min="0.01" :step="1" :precision="2" class="AdjustItem-qty-number"/>
          <span class="AdjustItem-qty-unit">{{ productDetail?.unit || '' }}</span>
        </div>
      </el-form-item>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="单位成本(¥)">
            <el-input :model-value="money(form.currentAvgCost)" disabled class="AdjustItem-form-input"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="当前库存">
            <div class="AdjustItem-stock">
              <el-input :model-value="toFixed(form.balanceQuantity)" disabled class="AdjustItem-form-input"/>
              <span class="AdjustItem-stock-unit">{{ productDetail?.unit || '' }}</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注">
        <el-input v-model="form.note" type="textarea" :rows="3" placeholder="可填写备注" class="AdjustItem-form-input"/>
      </el-form-item>
    </el-form>

    <el-alert v-if="loading" title="正在加载商品信息..." type="info" :closable="false" class="AdjustItem-tip"/>
    <el-alert v-else-if="!productDetail" title="未获取到商品信息" type="warning" :closable="false"
              class="AdjustItem-tip"/>

    <template #footer>
      <div class="AdjustItem-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="!productDetail">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {ref, reactive, watch} from 'vue'
import {getProduct} from '../../../api/productApi.js'
import {ElMessage} from 'element-plus'

const props = defineProps({
  visible: {type: Boolean, default: false},
  mode: {type: String, default: 'damage'},
  productId: {type: [Number, String], default: null}
})
const emits = defineEmits(['update:visible', 'confirm'])

const dialogVisible = ref(false)
const formRef = ref()
const form = reactive({date: '', quantity: null, currentAvgCost: 0, balanceQuantity: 0, note: '', operation: ''})
const productDetail = ref(null)
const loading = ref(false)

const rules = reactive({
  // 移除 date 必填规则（日期固定且禁用，不显示星号）
  quantity: [
    {required: true, message: '请输入数量', trigger: 'change'},
    {
      validator: (_r, v, cb) => {
        const num = Number(v)
        if (!num || num <= 0) return cb(new Error('数量需大于0'))
        if (props.mode === 'damage') {
          const stock = Number(form.balanceQuantity || 0)
          if (num > stock) return cb(new Error('报损数量不能超过当前库存'))
        }
        cb()
      }, trigger: 'change'
    }
  ],
  note: [
    { validator: (_r, v, cb) => { if (v && v.length > 100) return cb(new Error('备注最多100个字符')); cb() }, trigger: 'blur' }
  ]
})

watch(() => props.visible, v => {
  dialogVisible.value = v;
  if (v) init()
})
watch(dialogVisible, v => {
  if (!v) emits('update:visible', false)
})
watch(() => props.productId, id => {
  if (dialogVisible.value && id) loadProduct()
})
watch(() => props.mode, (m) => {
  form.operation = m === 'damage' ? 'damage' : 'overflow'
})

const todayStr = () => {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

const init = () => {
  form.date = todayStr()
  form.quantity = 1 // 默认数量 1.00
  form.note = ''
  form.currentAvgCost = 0
  form.balanceQuantity = 0
  form.operation = props.mode === 'damage' ? 'damage' : 'overflow'
  productDetail.value = null
  if (props.productId) loadProduct()
}

const loadProduct = async () => {
  if (!props.productId) return
  loading.value = true
  try {
    const res = await getProduct(props.productId)
    productDetail.value = res || null
    if (res) {
      form.currentAvgCost = Number(res.currentAvgCost || 0)
      form.balanceQuantity = Number(res.balanceQuantity || 0)
    }
  } catch (e) {
    productDetail.value = null
    ElMessage.error('加载商品信息失败')
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
}
const handleConfirm = async () => {
  try {
    await formRef.value?.validate()
    if (props.mode === 'damage') {
      const qty = Number(form.quantity || 0)
      const stock = Number(form.balanceQuantity || 0)
      if (qty > stock) {
        ElMessage.error('报损数量不能超过当前库存')
        return
      }
    }
    emits('confirm', {
      productId: props.productId,
      date: form.date,
      quantity: Number(form.quantity),
      currentAvgCost: Number(form.currentAvgCost),
      balanceQuantity: Number(form.balanceQuantity),
      note: form.note,
      operation: form.operation
    })
  } catch (e) { /* ignore */ }
}

const toFixed = v => Number(v || 0).toFixed(2)
const money = v => Number(v || 0).toFixed(2)
</script>
<style scoped lang="scss">
.AdjustItem {
  &-product {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
    padding-bottom: 16px;
    border-bottom: 1px solid #eee;
  }

  &-product-item {
    font-size: 14px;
    color: #303133;
  }

  &-product-label {
    color: #606266;
  }

  &-form {
    padding: 16px 0;
  }

  &-form-input {
    width: 100%;
  }

  &-tip {
    margin-top: 8px;
  }

  &-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
  }

  &-qty {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  &-qty-number {
    width: 160px;
  }

  &-qty-unit {
    color: #606266;
    min-width: 32px;
  }

  &-stock {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  &-stock-unit {
    color: #606266;
    min-width: 32px;
  }
}
</style>
